package ac.neec.mio.ui.activity;

import ac.neec.core.ble.util.BleUtil;
import ac.neec.data.SpecificActivities;
import ac.neec.data.User;
import ac.neec.listener.EventsCallBackListener;
import ac.neec.listener.HeartRateEventListener;
import ac.neec.mio.R;
import ac.neec.mio.ui.fragment.ConnectBLEFlagment;
import ac.neec.mio.ui.fragment.MeasurementHeartRateFlagment;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by kobayashi on 2014/01/26.
 */
public class MeasurementActivity extends BLEActivity implements
		EventsCallBackListener<Object> {
	public static final String BACK_STACK_BLE_CONNECT_ADD = "BLE Connect Setting ADD";
	public static final String BACK_STACK_HEART_RATE_FRAGMENT_ADD = "HeartRateFragment ADD";
	public static final int CALLBACK_ID_CONNECT_BLE_FRAGMENT = 10;
	public static final int CALLBACK_ID_MEASUREMENT_START = 11;
	public static final int CALLBACK_ID_MEASUREMENT_STOP = 12;
	private static final int REQUEST_ENABLE_BLUETOOTH = 0;
	private HeartRateEventListener<Object> mEventListener;
	private SpecificActivities specificActivities;
	private User user;
	private float pointMETs;
	private int pointLevel;
	private int theoryLevel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_measurement_main);

		specificActivities = (SpecificActivities) getIntent()
				.getSerializableExtra("SpecificActivities");
		user = (User) getIntent().getSerializableExtra("user");
		pointMETs = Float.valueOf(getIntent().getStringExtra("pointMETs"));
		pointLevel = Integer.valueOf(getIntent().getStringExtra("pointLevel")
				.split("%")[0]);
		theoryLevel = Integer.valueOf(getIntent().getStringExtra("theoryLevel")
				.split("%")[0]);
		startupBluetooth();
		setupOnCreate();
	}

	private void startupBluetooth() {
		// TODO BLE Support check
		if (!BleUtil.isBLESupported(this)) {
			Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT)
					.show();
			finish();
		}
		BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
		if (btAdapter == null) {
			// alertBluetoothUnsupported();
		} else {
			if (!btAdapter.isEnabled()) {
				Intent intent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(intent, REQUEST_ENABLE_BLUETOOTH);
			} else {
				startupConnectBLEFragment();
			}
		}
	}

	private void startupConnectBLEFragment() {
		ConnectBLEFlagment fragment = new ConnectBLEFlagment();
		FragmentTransaction transaction = getFragmentManager()
				.beginTransaction();
		transaction.add(R.id.act_measurement_main_container, fragment);
		transaction.addToBackStack(BACK_STACK_BLE_CONNECT_ADD);
		transaction.commit();

	}

	private void startupHeartRateMeasurement(BluetoothDevice device) {
		// TODO Connect BLE Device
		setupBLEConnect(device, this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setupOnResume();

	}

	@Override
	protected void onPause() {
		super.onPause();
		setupOnPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		setupOnDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int ResultCode, Intent date) {
		if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
			if (ResultCode == Activity.RESULT_OK) {
				startupConnectBLEFragment();
			} else {
				// alertBluetoothUnAccept();
				// TODO
				Toast.makeText(getApplicationContext(), "Bluetooth unactive",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	protected void updateConnectionState(int resourceId) {
//		Toast.makeText(getApplicationContext(), "CONNECT OK", 0).show();
	}

	@Override
	protected void clearUI() {

	}

	@Override
	protected void displayData(final String data) {
		if(mEventListener == null){
			Log.e("EventListener", "null pointer");
		}
		else{
		mEventListener.notifyHeartRateEvent(data);
		}
	}

	@Override
	public void onCallBack(int id, Object value) {
		switch (id) {
		case CALLBACK_ID_CONNECT_BLE_FRAGMENT:
			BluetoothDevice device = (BluetoothDevice) value;
			startupHeartRateMeasurement(device);
			break;
		case CALLBACK_ID_MEASUREMENT_START:
			setupReadCharacteristic();
			setupOnResume();
			break;
		case CALLBACK_ID_MEASUREMENT_STOP:
			finish();
			break;
		}
	}

	@Override
	protected void notifyServiceConnecttion(boolean flag) {
		if (flag == false)
			return;
		MeasurementHeartRateFlagment fragment = new MeasurementHeartRateFlagment();
		try {
			mEventListener = (HeartRateEventListener) fragment;
		} catch (ClassCastException e) {
			throw new ClassCastException(fragment.toString()
					+ " must implement OnArticleSelectedListener");
		}
		setupOnCreate();
		Bundle bundle = new Bundle();
		bundle.putInt("theoryLevel", theoryLevel);
		bundle.putInt("pointLevel", pointLevel);
		bundle.putFloat("theoryMETs", specificActivities.getMets());
		bundle.putFloat("pointMETs", pointMETs);
		bundle.putSerializable("specificActivities", specificActivities);
		bundle.putSerializable("user", user);
		fragment.setArguments(bundle);
		FragmentTransaction transaction = getFragmentManager()
				.beginTransaction();
		transaction.replace(R.id.act_measurement_main_container, fragment);
		transaction.addToBackStack(BACK_STACK_HEART_RATE_FRAGMENT_ADD);
		transaction.commit();

	}

}
